package com.yonyou.hrcloud.ncc.staff.web;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.hrcloud.adder.context.AppContext;
import com.yonyou.hrcloud.adder.model.param.PagerRequest;
import com.yonyou.hrcloud.adder.model.param.Sorter;
import com.yonyou.hrcloud.adder.model.query.Condition;
import com.yonyou.hrcloud.adder.model.query.IExpression;
import com.yonyou.hrcloud.adder.model.query.LogicExpression;
import com.yonyou.hrcloud.adder.model.query.Operator;
import com.yonyou.hrcloud.adder.model.query.SqlExpression;
import com.yonyou.hrcloud.adder.model.query.ValueExpression;
import com.yonyou.hrcloud.berry.helper.HRCloudRefHelper;
import com.yonyou.hrcloud.commons.staff.model.CommonSimpleStaff;
import com.yonyou.hrcloud.commons.staff.service.ICommonSimpleStaffService;
import com.yonyou.hrcloud.ncc.helper.NccRetrieveHelper;
import com.yonyou.hrcloud.ncc.org.web.OrgTreeGridRefController;
import com.yonyou.hrcloud.ncc.staff.service.ICommonStaffPowerService;
import com.yonyou.iuap.ref.model.RefViewModelVO;

import nc.jdbc.framework.processor.ResultSetProcessor;

@org.springframework.web.bind.annotation.RestController
@org.springframework.web.bind.annotation.RequestMapping({"/ref/xcstaff_tree_grid_ref"})
public class XCStaffTreeGridRefController extends OrgTreeGridRefController<CommonSimpleStaff> {

	private static final Logger log = LoggerFactory.getLogger(StaffTreeGridRefController.class);

	private String SIMPLESTAFF_ONDUTY_MAIN_CON = "bd_psndoc.dr=0 and hi_psnorg.dr=0 and hi_psnjob.dr=0 and hi_psnorg.lastflag='Y' and hi_psnjob.lastflag='Y' and hi_psnjob.psntype=0 and hi_psnorg.indocflag='Y' and hi_psnjob.ismainjob = 'Y' and hi_psnjob.endflag='N' and bd_psndoc.enablestate=2";

	private String SIMPLESTAFF_ONDUTY_MAINPART_CON = "bd_psndoc.dr=0 and hi_psnorg.dr=0 and hi_psnjob.dr=0 and hi_psnorg.lastflag='Y' and hi_psnjob.lastflag='Y' and hi_psnjob.psntype=0 and hi_psnorg.indocflag='Y' and hi_psnjob.endflag='N' and bd_psndoc.enablestate=2";

	@Resource
	private ICommonSimpleStaffService staffQueryService;

	@Resource
	private ICommonStaffPowerService staffQueryPowerService;
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, String>> blobRefClassSearch(RefViewModelVO refViewModel) {
		
		String sql = "select * from view_smg_zwxldoc";
		
		List<Map<String, String>> result = (List<Map<String, String>>) NccRetrieveHelper.executeQuery(sql, new ResultSetProcessor() {
			
			@Override
			public Object handleResultSet(ResultSet rs) throws SQLException {
				ResultSetMetaData metaData = rs.getMetaData();
				int cols = metaData.getColumnCount();
				List<Map<String, String>> result = new ArrayList<Map<String,String>>();
				while (rs.next()) {
					Map<String, String> rsValues = new HashMap<String, String>();
					for (int i = 1; i <= cols; i++) {
						
						Object value = rs.getObject(i) == null ? "" : "" + rs.getObject(i);
						String propName = metaData.getColumnLabel(i);
						if (propName == null) {
							propName = metaData.getColumnName(i);
						}
						
						rsValues.put(propName, (String) value);
					}
					
					result.add(rsValues);
				}
				
				return result;
			}
		});
		
		return result;
	}

	public List<Map<String, String>> matchPKRefJSON(@RequestBody RefViewModelVO refViewModel) {
		HRCloudRefHelper.setContextInfo(refViewModel);
		String[] ids = refViewModel.getPk_val();
		if ((ids == null) || (ids.length == 0)) {
			return null;
		}
		List staffs = this.staffQueryService.querySimpleStaffListByIds(Arrays.asList(ids));
		return createResult(staffs);
	}

	protected String getCodeField() {
		return "bd_psndoc.code";
	}

	protected String getNameField() {
		return "bd_psndoc.name";
	}

	protected Sorter getSorter() {
		return null;
	}

	protected void addConditionByLeftTree(Condition condition, String leftConditionValue, boolean ignoreOrgCon) {
		if (StringUtils.isNotEmpty(leftConditionValue))
			condition.addExpressions(
					new IExpression[] { new LogicExpression(new ValueExpression("hi_psnjob.pk_org", leftConditionValue),
							new ValueExpression("hi_psnjob.jobglbdef4", leftConditionValue), true) });
		else if (!ignoreOrgCon)
			condition.addExpressions(new IExpression[] { new SqlExpression("1=2") });
	}

	protected void addClientParams(Condition condition, RefViewModelVO ref) {
		String clientParam = ref.getClientParam();
		if (StringUtils.isBlank(clientParam)) {
			condition.addExpressions(new IExpression[] { new SqlExpression(this.SIMPLESTAFF_ONDUTY_MAIN_CON) });
			return;
		}
		JSONObject json = JSON.parseObject(clientParam);
		String in = json.getString("inOrgIds");
		String notin = json.getString("notInOrgIds");
		String includePart = json.getString("includePart");
		String userId = AppContext.getContext().getUserId();
		String tenantId = AppContext.getContext().getScope();

		if ("true".equalsIgnoreCase(includePart))
			condition.addExpressions(new IExpression[] { new SqlExpression(this.SIMPLESTAFF_ONDUTY_MAINPART_CON) });
		else {
			condition.addExpressions(new IExpression[] { new SqlExpression(this.SIMPLESTAFF_ONDUTY_MAIN_CON) });
		}
		if (StringUtils.isNotBlank(in)) {
			condition.addExpression("hi_psnjob.pk_org", in.split(","), Operator.IN);
		}
		if (StringUtils.isNotBlank(notin))
			condition.addExpression("hi_psnjob.pk_org", notin.split(","), Operator.NOTIN);
	}

	@Override
	protected List<Map<String, String>> createResult(List<CommonSimpleStaff> staffs) {
		List m = new ArrayList();
		if (CollectionUtils.isEmpty(staffs))
			return m;
		for (CommonSimpleStaff staff : staffs) {
			Map map = new HashMap();
			map.put("refpk", staff.getId());
			map.put("refcode", staff.getCode());
			map.put("refname", staff.getName());
			map.put("id", staff.getId());
			map.put("deptId", staff.getDeptId());
			map.put("deptName", staff.getDeptName());
			map.put("psnlName", staff.getPsnclName());
			map.put("staffCode", staff.getCode());
			map.put("orgName", staff.getOrgName());
			map.put("orgId", staff.getOrgId());
			map.put("ismainjob", staff.getIsmainjob() != null ? staff.getIsmainjob().toString() : "true");
			m.add(map);
		}
		return m;
	}

	@Override
	protected List<CommonSimpleStaff> queryListByConditon(Condition condition, Sorter sorter, String serviceCode,
			String user, String group) {
		return this.staffQueryPowerService.queryPowerAllStaffListByCondition(condition, sorter, serviceCode, user,
				group);
	}

	@Override
	protected Page<CommonSimpleStaff> queryPageByConditon(Condition condition, Pageable pageable, String serviceCode,
			String user, String group) {
		int page = ((PagerRequest) pageable).getPageNumber();
		PagerRequest pageablenew = new PagerRequest(page, 1000);
		Page<CommonSimpleStaff> pageResult = this.staffQueryPowerService.queryPowerAllStaffsPage(condition, pageablenew,
				serviceCode, user, group);
		if (pageResult.getTotalElements() == 0L)
			return pageResult;
		for (CommonSimpleStaff staff : pageResult.getContent()) {
			staff.setName(staff.getName() + "(" + staff.getCode() + ")-" + staff.getDeptName());
		}
		return pageResult;
	}

	@Override
	protected String getPrimaryField() {
		return "id";
	}

	@Override
	protected Class<CommonSimpleStaff> getRefClass() {
		return CommonSimpleStaff.class;
	}
}
